
// 查询 find
let getBooks = (ctx, cb) => {

  let tableId = getApp().globalData.tableId, // 表ID
    Books = new wx.BaaS.TableObject(tableId), // 根据表ID,初始化表对象
    openid = ctx.data.openid  // 获取openid

  // 条件查询
  let query = new wx.BaaS.Query();
  query.contains('openid', openid);

  // 分页查询（默认limit为20,offset为0,limit最大1000）

  // 查询排序
  // .orderBy('-created_at') // 降序
  // .orderBy('created_at')  // 升序

  Books.setQuery(query).limit(15).offset(0).orderBy('-created_at').find()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

// 新增 set
let addBook = (ctx, cb) => {

  let tableId = getApp().globalData.tableId,
    Books = new wx.BaaS.TableObject(tableId),
    Book = Books.create(),
    bookName = ctx.data.creatingBookName, // 获取书名
    openid = ctx.data.openid  // 获取openid

  // 新增的字段一定要先在『后台表』里面创建，才能提交上去

  let data = {
    bookName,
    openid
  }

  Book.set(data)
    .save()
    .then(res => cb(res))
    .catch(err => console.dir(err))

}

// 更新 set update（根据记录ID）
let updateBook = (ctx, cb) => {

  let tableId = getApp().globalData.tableId,
    recordId = ctx.data.curRecordId,
    bookName = ctx.data.editingBookName

  let Books = new wx.BaaS.TableObject(tableId),
    Book = Books.getWithoutData(recordId) // 通过 recordID 设置指定记录

  let data = {
    bookName
  }

  Book.set(data)
    .update()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

// 删除 delete （根据记录ID）
let deleteBook = (ctx, cb) => {

  let tableId = getApp().globalData.tableId,
    recordId = ctx.data.curRecordId

  let Books = new wx.BaaS.TableObject(tableId)

  Books.delete(recordId)
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

// 查询 用户
let getUser = (ctx, cb) => {

  let MyUser = new wx.BaaS.User(),
    openid = ctx.data.openid  // 获取openid

  // 条件查询
  let query = new wx.BaaS.Query();
  query.contains('openid', openid);

  MyUser.setQuery(query).find()
    .then(res => cb(res))
    .catch(err => console.dir(err));
}

module.exports = {
  getBooks,
  addBook,
  updateBook,
  deleteBook,
  getUser,
}